import os
import time
from tkinter import *
from tkinter import messagebox
from tkinter import Canvas
import random
from PIL import Image, ImageTk
import pymysql
import _thread

ti = 600
victory = 0
playerMachine = 1
stop_threads = True


# 创建地图所需的二维数组
def MapCreator(m, n, MaxEcnt):
    # 从起始点开始随机行走，走到不能再走为止
    def inborder(x, y):
        return x < n and x >= 0 and y < m and y >= 0

    # 记录每个点是否经过过
    visited = [[False for i in range(m)] for j in range(n)]
    # 记录迷宫形状，注意n行,m列的迷宫应该包含2n+1行，2m+1列
    # 因为a条平行的通路之间和两侧一共还有a+1堵墙
    map = [[0 for i in range(2 * m + 1)] for j in range(2 * n + 1)]
    dx = [-1, 1, 0, 0]
    dy = [0, 0, -1, 1]
    # 分别是上下左右的位移矢量
    # 起始点位置和终止点位置
    startposx = 0
    startposy = 0
    endposx = m - 1
    endposy = n - 1
    # px，py是指针当前指向的位置，visited[px][py]对应于map[2px+1][2py+1]
    px = startposx
    py = startposy
    visited[px][py] = True
    visitedpos = [(px, py)]  # 之前走过的所有点构成的列表
    map[2 * px + 1][2 * py + 1] = 1
    sum = 1  # 经过点的总数，当达到mn时迷宫就构建好了
    while (sum < m * n):
        walkable = []  # 存储px，py点前后左右四个点中能到达的点对应的i
        for i in range(4):
            # 计算新的点的位置
            tx = px + dx[i]
            ty = py + dy[i]
            if inborder(tx, ty) and not visited[tx][ty]:  # 能到达就将i加入walkable
                walkable.append(i)
        if not walkable or (px == endposx and py == endposy):
            # 如果walkable为空，或已到达终点，则向之前的位置随机传送
            px, py = random.choice(visitedpos)
        else:
            # 随机选择方向行进
            i = random.choice(walkable)
            px += dx[i]
            py += dy[i]
            visited[px][py] = True
            visitedpos.append((px, py))
            # 将到达的点和前后两点之间的墙赋值为1（路）
            map[2 * px + 1][2 * py + 1] = 1
            map[2 * px + 1 - dx[i]][2 * py + 1 - dy[i]] = 1
            sum += 1

    # 返回map
    global smap
    smap = []
    ecnt = 0
    for j in range(2 * n + 1):
        s = ""
        for i in range(2 * m + 1):
            r = random.random()
            if map[j][i]:
                if (r >= 0 and r < 0.1):
                    s += 'G'
                elif (r >= 0.1 and r < 0.15 and ecnt < MaxEcnt):
                    s += 'E'
                    ecnt += 1
                else:
                    s += ' '
            else:
                s += '@'
        smap.append(s)


# 初始界面
def tianmei():
    # 返回界面/删除初始界面的
    def back(event):
        frame00.pack_forget()
        root00.destroy()

    root00 = Tk()
    root00.title("按任意键继续！")
    root00.geometry("600x340+330+100")
    file = "photo/timi.gif"
    img = Image.open(file)  # 打开图片
    timi = ImageTk.PhotoImage(img)
    frame00 = Frame(root00, bd=3, width=575, height=330)
    frame00.pack()
    Label(frame00, image=timi).pack()
    root00.bind("<KeyPress>", back)
    root00.bind("<Button>", back)
    root00.mainloop()


# 登陆界面
def loginUi():
    # 注册界面
    def reLogin():
        # 注册步骤
        def zhuce():
            if newPhone.get() and newPwd.get() and newUser:
                cursor.execute('select * from wanjia where name=%s', (str(newUser.get())))
                # 如果找到，则登录成功
                if cursor.fetchall():
                    messagebox.showinfo("提示！", "注册失败！已有该用户！")
                else:
                    sql = 'insert into wanjia values("' + str(newUser.get()) + '",' + str(newPwd.get()) + ',' + str(
                        newPhone.get()) + ',' + '0)'
                    print(sql)
                    cursor.execute(sql)
                    db.commit()
                    messagebox.showinfo("提示！", "注册成功！开始游戏吧！")
                    reLoginFrame.pack_forget()
                    frameLogin.pack()

        def ret():
            reLoginFrame.pack_forget()
            frameLogin.pack()

        frameLogin.pack_forget()
        reLoginFrame = Frame(master=root, width=430, height=390, bd=3, bg="pink", relief="ridge")
        reLoginFrame.pack()
        label0 = Label(reLoginFrame, text=" 用 户 名 ")
        label0.grid(row=0, column=0)
        entry0 = Entry(reLoginFrame, textvariable=newUser)
        entry0.grid(row=0, column=1)

        label1 = Label(reLoginFrame, text=" 密     码 ")
        label1.grid(row=1, column=0)
        entry1 = Entry(reLoginFrame, textvariable=newPwd, show="*")
        entry1.grid(row=1, column=1)

        label2 = Label(reLoginFrame, text=" 手 机 号 ")
        label2.grid(row=2, column=0)
        entry2 = Entry(reLoginFrame, textvariable=newPhone)
        entry2.grid(row=2, column=1)

        Label(reLoginFrame, text='', bg="pink").grid(row=3, column=3)

        btn1 = Button(reLoginFrame, text="确 认 注 册", command=zhuce)
        btn1.grid(row=4, column=1)
        btn2 = Button(reLoginFrame, text="返 回", command=ret)
        btn2.grid(row=4, column=0)

    # 登陆判断
    def Login():
        cursor.execute('select * from wanjia where name=%s and password=%s', (str(user.get()), str(pwd.get())))
        # 如果找到，则登录成功
        if cursor.fetchall():
            cursor.execute('select * from wanjia where name=%s and password=%s', (str(user2.get()), str(pwd2.get())))
            if cursor.fetchall():
                frameLogin.pack_forget()
                root.destroy()
                Game()
            else:
                messagebox.showinfo("提示！", "玩家2信息输入有误")
        else:
            messagebox.showinfo("提示！", "玩家1信息输入有误")

    # 找回密码
    def recover(event):
        def pan():
            if recoverCaptcha.get() == captcha.get():
                cursor.execute('select * from wanjia where name=%s and phone=%s',
                               (str(recoverUser.get()), str(recoverPhone.get())))
                if cursor.fetchall():

                    if str(recoverPwd.get()):
                        sql = 'update wanjia set password = "' + str(recoverPwd.get()) + '" where name="' + str(
                            recoverUser.get()) + '"'
                        print(sql)
                        cursor.execute(sql)
                        db.commit()
                        messagebox.showinfo('窗口', "密码修改成功")
                        hui()
                    else:
                        messagebox.showinfo('窗口', "新密码不能为空！请重新输入")

                else:
                    messagebox.showinfo('窗口', "用户名不存在或者密码错误！请重新输入")
            else:
                messagebox.showinfo('窗口', "验证码错误！请重新输入")
                Ma()

        def Ma():
            ma = []
            for i in range(65, 91):
                ma.append(chr(i))
            for i in range(0, 10):
                ma.append(str(i))
            for i in range(97, 123):
                ma.append(chr(i))
            captcha.set('')
            p = ''.join(random.sample(ma, 4))
            captcha.set(p)
            print(captcha.get())
            label05.config(text=captcha.get())

        def hui():
            recoverFrame.pack_forget()
            recoverFrame.destroy()
            frameLogin.pack()

        frameLogin.pack_forget()
        recoverFrame = Frame(master=root, width=430, height=390, bd=3, bg="pink", relief="ridge")
        recoverFrame.pack()
        recoverUser = StringVar()
        recoverPwd = StringVar()
        recoverPhone = StringVar()
        captcha = StringVar()
        recoverCaptcha = StringVar()

        label00 = Label(recoverFrame, text=" 用 户 名 ")
        user.set("阿罗")
        label00.grid(row=0, column=0)
        entry00 = Entry(recoverFrame, textvariable=recoverUser)
        entry00.grid(row=0, column=1)
        label02 = Label(recoverFrame, text=" 手 机 号 ")
        label02.grid(row=1, column=0)
        entry01 = Entry(recoverFrame, textvariable=recoverPhone)
        entry01.grid(row=1, column=1)
        label03 = Label(recoverFrame, text=" 验 证 码 ")
        label03.grid(row=2, column=0)
        label05 = Label(recoverFrame, text=captcha.get())
        Ma()
        label05.grid(row=2, column=2)
        btn02 = Button(recoverFrame, text="点击更换", command=Ma)
        btn02.grid(row=2, column=3)
        entry03 = Entry(recoverFrame, textvariable=recoverCaptcha)
        entry03.grid(row=2, column=1)

        label04 = Label(recoverFrame, text=" 新 密 码 ")
        label04.grid(row=3, column=0)
        entry04 = Entry(recoverFrame, textvariable=recoverPwd)
        entry04.grid(row=3, column=1)
        btn03 = Button(recoverFrame, text="确定", command=pan)
        btn03.grid(row=4, column=1)

        btn04 = Button(recoverFrame, text="返回", command=hui)
        btn04.grid(row=4, column=0)

    root = Tk()
    root.title("窗口")
    root.geometry("600x340+330+100")
    frameLogin = Frame(master=root, width=430, height=390, bd=3, bg="pink", relief="ridge")
    frameLogin.pack()
    global user, pwd, user2, pwd2

    user = StringVar()
    pwd = StringVar()
    user2 = StringVar()
    pwd2 = StringVar()
    newUser = StringVar()
    newPwd = StringVar()
    newPhone = StringVar()

    label000 = Label(frameLogin, text=" 用 户 名1 ")
    user.set("阿罗")
    label000.grid(row=0, column=0)
    entry000 = Entry(frameLogin, textvariable=user)
    entry000.grid(row=0, column=1)

    label001 = Label(frameLogin, text=" 密     码1 ")
    pwd.set("200174al")
    label001.grid(row=1, column=0)
    entry001 = Entry(frameLogin, textvariable=pwd, show="*")
    entry001.grid(row=1, column=1)

    label0000 = Label(frameLogin, text=" 用 户 名2 ")
    label0000.grid(row=2, column=0)
    user2.set("互补亲")
    entry0000 = Entry(frameLogin, textvariable=user2)
    entry0000.grid(row=2, column=1)

    label0010 = Label(frameLogin, text=" 密     码2 ")
    label0010.grid(row=3, column=0)
    pwd2.set('123')
    entry0010 = Entry(frameLogin, textvariable=pwd2, show="*")
    entry0010.grid(row=3, column=1)

    Label(frameLogin, text='', bg="pink").grid(row=4, column=3)

    btn000 = Button(frameLogin, text="登 录", command=Login)
    btn000.grid(row=5, column=0)
    btn001 = Button(frameLogin, text="注 册", command=reLogin)
    btn001.grid(row=5, column=1)

    text000 = Text(frameLogin, width=10, height=1, bg="white")
    text000.insert(1.0, "忘记密码")
    text000.tag_add("a", 1.0, 1.8)
    text000.tag_config('a', underline=True)
    text000.tag_bind("a", "<1>", recover)
    text000.grid(row=4, column=1)

    root.mainloop()


def update():
    global ti, stop_threads
    ti = 600
    while True:
        if stop_threads:
            pass
        else:
            time_label['text'] = 600
            time_label1['text'] = 600
            stop_threads = True
            break
        time_label['text'] = ti
        time_label1['text'] = ti
        time.sleep(1)
        ti -= 1
        if ti == 0:
            break


# 迷宫各项属性设置界面
def setUp():
    def machine():
        global playerMachine
        if str(radvar.get()) == "双人模式":
            playerMachine = 1
        elif str(radvar.get()) == "单人模式":
            playerMachine = 2
        else:
            playerMachine = 0

    def OK():
        global p, m, n, es, eqi, player, play
        p = int(ee.get())
        m = int(mm.get())
        n = int(nn.get())
        es = int(esu.get())
        eqi = int(eq.get())
        setFrame.destroy()
        MapCreator(n, m, p)
        frame.pack()
        frameplay1.pack(side="left", fill=BOTH, expand=YES)
        createCanvas.pack(side="left", fill=BOTH, expand=YES)
        frameplay2.pack(side="left", fill=BOTH, expand=YES)
        play = player(createCanvas)
        _thread.start_new_thread(update, ())

    global setFrame

    setFrame = Frame(root, width=590, height=330, bd=3, bg="pink", padx=80, pady=80)
    setFrame.pack()
    label000 = Label(setFrame, text="迷 宫 设 置 ！", font="宋体")
    label000.grid(row=0, columnspan=2, pady=15)

    label001 = Label(setFrame, text="迷宫长度(2*x+1):(x <= 15)")
    label001.grid(row=1, column=0)
    mm, nn, ee, esu, eq = StringVar(), StringVar(), StringVar(), StringVar(), StringVar()
    nn.set(n)
    entry001 = Entry(setFrame, textvariable=nn)
    entry001.grid(row=1, column=1)

    label002 = Label(setFrame, text="迷宫高度(2*x+1):(x <= 14)")
    label002.grid(row=2, column=0)
    mm.set(m)
    entry002 = Entry(setFrame, textvariable=mm)
    entry002.grid(row=2, column=1)

    label003 = Label(setFrame, text=" 迷 宫 恶 魔 数  :(x <= 20)")
    label003.grid(row=3, column=0)
    ee.set(p)
    entry003 = Entry(setFrame, textvariable=ee)
    entry003.grid(row=3, column=1)

    label004 = Label(setFrame, text="迷 宫 恶魔 速 度:(越小越快)")
    label004.grid(row=4, column=0)
    esu.set(1000)
    entry004 = Entry(setFrame, textvariable=esu)
    entry004.grid(row=4, column=1)

    label005 = Label(setFrame, text="迷 宫 恶魔 实 力:(越小越强)")
    label005.grid(row=5, column=0)
    eq.set(80)
    entry005 = Entry(setFrame, textvariable=eq)
    entry005.grid(row=5, column=1)

    label006 = Label(setFrame, bg='pink')
    label006.grid(row=6, column=0)

    radvar = StringVar()
    radvar.set("双人模式")

    rad0 = Radiobutton(setFrame, text="人机模式", value="人机模式", variable=radvar, command=machine)
    rad0.grid(row=7, column=0)

    rad1 = Radiobutton(setFrame, text="双人模式", value="双人模式", variable=radvar, command=machine)
    rad1.grid(row=7, column=1)

    rad2 = Radiobutton(setFrame, text="单人模式", value="单人模式", variable=radvar, command=machine)
    rad2.grid(row=7, column=2, padx=40)

    btn001 = Button(setFrame, text="确认！", command=OK)
    btn001.grid(row=8, column=1, pady=10)

    btn002 = Button(setFrame, text="返回！", command=back)
    btn002.grid(row=8, column=0)


# 返回函数
def back():
    setFrame.destroy()
    frame.destroy()
    root.destroy()
    loginUi()


# 画板类方便扩展
class drawingBoard(Canvas):
    def __init__(self, master=NONE, **kw):
        super().__init__(master, width=n * 2 * 24 + 8 * n, height=2 * m * 24 + 8 * m, bd=3)
        self.master = master
        self.pack()


# 画迷宫的类
class player(drawingBoard):
    def __init__(self, master=NONE, **kw):
        super().__init__(master)
        global playerMachine, victory
        self.master = master
        self.stop = 0
        self.px = 1
        self.py = 1
        self.pi = pr
        self.px2 = 2 * n - 1
        self.py2 = 1
        self.pi2 = pl
        self.Emo = []
        self.emo1 = []
        self.demon = {}
        self.d = {}
        self.createPlayer()
        if playerMachine == 1:
            self.createPlayer2()
        elif playerMachine == 2:
            frameplay2.pack_forget()
            self.play2 = self.create_image(0, 0, image=pr)
        else:
            self.createMachinePlayer()
        self.createMz()

    def createMz(self):
        for index, value in enumerate(smap):
            c = []
            i = 0
            for rowIndex, rowValue in enumerate(value):
                c.append(rowValue)
                if rowValue == '@':
                    self.create_image(4 * n + rowIndex * 24, m * 4 + index * 24, image=wall)
                elif rowValue == "E":
                    self.demon[str(i)] = self.create_image(4 * n + rowIndex * 24, m * 4 + index * 24, image=e)
                    self.demonLoop(self.demon[str(i)])
                    self.demonLooppan(self.demon[str(i)])
                    i += 1
                elif rowValue == "G":
                    a = str(rowIndex) + str(index)
                    self.d[a] = self.create_image(4 * n + rowIndex * 24, m * 4 + index * 24,
                                                  image=gold)
            self.Emo.append(c)
            self.emo1.append(c)

        if playerMachine == 0:
            self.direction1()
            self.MachinePlayerMove()

    def createMachinePlayer(self):
        self.play2 = self.create_image(4 * n + (2 * n - 1) * 24, m * 4 + 24, image=pl)

    def direction1(self):
        global lst
        lst = [(1, 2 * n - 1, 'n')]
        while lst:
            now = lst[-1]
            row, col, dir = now
            if row == 2 * m - 1 and col == 1:
                break
            self.emo1[row][col] = '$'
            if self.emo1[row - 1][col] != '@' and self.emo1[row - 1][col] != '$':
                lst.append((row - 1, col, 'U'))
                continue
            elif self.emo1[row + 1][col] != '@' and self.emo1[row + 1][col] != '$':
                lst.append((row + 1, col, 'D'))
                continue
            elif self.emo1[row][col + 1] != '@' and self.emo1[row][col + 1] != '$':
                lst.append((row, col + 1, 'R'))
                continue
            elif self.emo1[row][col - 1] != '@' and self.emo1[row][col - 1] != '$':
                lst.append((row, col - 1, 'L'))
                continue
            else:
                lst.pop()

    def popLst(self):
        if lst[1]:
            now = lst[1]
            row, col, dir = now
            del lst[1]
            return row, col, dir
        return

    def MachineMove(self):
        row, col, dir = self.popLst()
        if dir == 'U':
            self.py2 -= 1
            self.delete(self.play2)
            self.play2 = self.create_image(col * 24 + 4 * n, row * 24 + m * 4, image=self.pi2)
        elif dir == 'D':
            self.py2 += 1
            self.delete(self.play2)
            self.play2 = self.create_image(col * 24 + 4 * n, row * 24 + m * 4, image=self.pi2)
        elif dir == 'L':
            self.px2 -= 1
            self.pi2 = pl
            self.delete(self.play2)
            self.play2 = self.create_image(col * 24 + 4 * n, row * 24 + m * 4, image=self.pi2)
        elif dir == 'R':
            self.px2 += 1
            self.pi2 = pr
            self.delete(self.play2)
            self.play2 = self.create_image(col * 24 + 4 * n, row * 24 + m * 4, image=self.pi2)

    def MachinePlayerMove(self):
        global loop1
        if self.stop == 1:
            pass
        else:
            self.machineTake()
            self.MachineMove()
            loop1 = self.after(1000, self.MachinePlayerMove)

    def machineTake(self):
        global stop_threads
        p = str(self.px2) + str(self.py2)
        global score2, label13
        if p in self.d.keys():
            score2 += 1
            a = "得分：" + str(score2)
            label13.config(text=a)
            self.delete(self.d[p])
            del self.d[p]
            if self.d:
                pass
            else:
                self.stop = 1
                if score2 > score1:
                    stop_threads = False
                    top()
                    messagebox.showinfo('提示', '游戏结束,玩家2获胜')
                    self.Over()

                elif score2 == score1:
                    stop_threads = False
                    top()
                    messagebox.showinfo('提示', '游戏结束,玩家2获胜')
                    self.Over()

                else:
                    stop_threads = False
                    top()
                    messagebox.showinfo('提示', '游戏结束,玩家1获胜')
                    self.Over()

    def createPlayer(self):
        self.play = self.create_image(4 * n + 24, m * 4 + 24, image=pr)
        root.bind("<KeyPress-Left>", self.playerMove)
        root.bind("<KeyPress-Up>", self.playerMove)
        root.bind("<KeyPress-Down>", self.playerMove)
        root.bind("<KeyPress-Right>", self.playerMove)
        root.bind("<KeyPress-p>", self.take)

    def take(self, event):
        global stop_threads
        global score1, label11
        p = str(self.px) + str(self.py)
        if p in self.d.keys():
            score1 += 1
            a = "得分：" + str(score1)
            label11.config(text=a)
            self.delete(self.d[p])
            del self.d[p]
            if self.d:
                pass
            else:
                self.stop = 1
                if score2 > score1:
                    stop_threads = False
                    top()
                    messagebox.showinfo('提示', '游戏结束,玩家2获胜')
                    self.Over()

                elif score2 == score1:
                    stop_threads = False
                    top()
                    messagebox.showinfo('提示', '游戏结束,玩家1获胜')
                    self.Over()

                else:
                    stop_threads = False
                    top()
                    messagebox.showinfo('提示', '游戏结束,玩家1获胜')
                    self.Over()

    def playerMove(self, event):
        if event.keycode == 37:
            self.playerLeft()
        elif event.keycode == 38:
            self.playerUp()
        elif event.keycode == 39:
            self.playerRigth()
        elif event.keycode == 40:
            self.playerDown()
        self.victoryPan()

    def playerLeft(self):
        if self.Emo[self.py][self.px - 1] == "@":
            pass
        else:
            self.px -= 1
            self.delete(self.play)
            self.pi = pl
            self.play = self.create_image(self.px * 24 + 4 * n, self.py * 24 + m * 4, image=self.pi)

    def playerUp(self):
        if self.Emo[self.py - 1][self.px] == "@":
            pass
        else:
            self.py -= 1
            self.delete(self.play)
            self.play = self.create_image(self.px * 24 + 4 * n, self.py * 24 + m * 4, image=self.pi)

    def playerRigth(self):
        if self.Emo[self.py][self.px + 1] == "@":
            pass

        else:
            self.px += 1
            self.pi = pr
            self.delete(self.play)
            self.play = self.create_image(self.px * 24 + 4 * n, self.py * 24 + m * 4, image=self.pi)

    def playerDown(self):
        if self.Emo[self.py + 1][self.px] == "@":
            pass
        else:
            self.py += 1
            self.delete(self.play)
            self.play = self.create_image(self.px * 24 + 4 * n, self.py * 24 + m * 4, image=self.pi)

    def createPlayer2(self):
        self.play2 = self.create_image(4 * n + (2 * n - 1) * 24, m * 4 + 24, image=pl)
        root.bind("<KeyPress-w>", self.playerMove2)
        root.bind("<KeyPress-a>", self.playerMove2)
        root.bind("<KeyPress-s>", self.playerMove2)
        root.bind("<KeyPress-d>", self.playerMove2)
        root.bind("<KeyPress-q>", self.take2)

    def take2(self, event):
        global stop_threads
        p = str(self.px2) + str(self.py2)
        global score2, label13
        if p in self.d.keys():
            score2 += 1
            a = "得分：" + str(score2)
            label13.config(text=a)
            self.delete(self.d[p])
            del self.d[p]
            if self.d:
                pass
            else:
                self.stop = 1
                if score2 > score1:
                    stop_threads = False
                    top()
                    messagebox.showinfo('提示', '游戏结束,玩家2获胜')
                    self.Over()

                elif score2 == score1:
                    stop_threads = False
                    top()
                    messagebox.showinfo('提示', '游戏结束,玩家2获胜')
                    self.Over()

                else:
                    stop_threads = False
                    top()
                    messagebox.showinfo('提示', '游戏结束,玩家1获胜')
                    self.Over()

    def playerMove2(self, event):
        if event.keycode == 65:
            self.playerLeft2()
        elif event.keycode == 87:
            self.playerUp2()
        elif event.keycode == 68:
            self.playerRigth2()
        elif event.keycode == 83:
            self.playerDown2()

    def playerLeft2(self):
        if self.Emo[self.py2][self.px2 - 1] == "@":
            pass
        else:
            self.px2 -= 1
            self.delete(self.play2)
            self.pi2 = pl
            self.play2 = self.create_image(self.px2 * 24 + 4 * n, self.py2 * 24 + m * 4, image=self.pi2)

    def playerUp2(self):
        if self.Emo[self.py2 - 1][self.px2] == "@":
            pass
        else:
            self.py2 -= 1
            self.delete(self.play2)
            self.play2 = self.create_image(self.px2 * 24 + 4 * n, self.py2 * 24 + m * 4, image=self.pi2)

    def playerRigth2(self):
        if self.Emo[self.py2][self.px2 + 1] == "@":
            pass
        else:
            self.px2 += 1
            self.pi2 = pr
            self.delete(self.play2)
            self.play2 = self.create_image(self.px2 * 24 + 4 * n, self.py2 * 24 + m * 4, image=self.pi2)

    def playerDown2(self):
        if self.Emo[self.py2 + 1][self.px2] == "@":
            pass
        else:
            self.py2 += 1
            self.delete(self.play2)
            self.play2 = self.create_image(self.px2 * 24 + 4 * n, self.py2 * 24 + m * 4, image=self.pi2)

    def demonLoop(self, a):
        global loop
        if self.stop == 1:
            pass
        else:
            self.moveDemon(a)
            loop = self.after(es, self.demonLoop, a)

    def demonLooppan(self, a):
        global loopPan
        if self.stop == 1:
            pass
        else:
            self.eatPlayer(a)
            loopPan = self.after(eqi, self.demonLooppan, a)

    def eatPlayer(self, a):
        demonCoordinate = []
        player1Coordinate = []
        player2Coordinate = []
        demonCoordinate.append(self.coords(a))
        player1Coordinate.append(self.coords(self.play))
        player2Coordinate.append(self.coords(self.play2))
        global life1, life2, label10, label12, victory, stop_threads
        if demonCoordinate == player1Coordinate:
            life1 -= 1
            if life1 == 0:
                self.stop = 1
                stop_threads = False
                top()
                if victory == 0:
                    victory = 1
                    messagebox.showinfo('提示', '游戏结束,玩家2获胜')
                self.Over()
            a = "生命:" + str(life1)
            label10.config(text=a)

        if demonCoordinate == player2Coordinate:
            life2 -= 1
            a = "生命:" + str(life2)
            label12.config(text=a)
            if life2 == 0:
                self.stop = 1
                stop_threads = False
                top()
                if victory == 0:
                    victory = 1
                    messagebox.showinfo('提示', '游戏结束,玩家1获胜')
                self.Over()

    def moveDirection(self, a, b, c):
        global direction, startOver

        if a[0][0] == b[0][0]:
            if a[0][1] > b[0][1]:
                direction = "U"
            elif a[0][1] == b[0][1]:
                direction = None
            else:
                direction = "D"

        if a[0][0] == c[0][0]:
            if a[0][1] > c[0][1]:
                direction = "U"
            elif a[0][1] == c[0][1]:
                direction = None
            else:
                direction = "D"

        if a[0][1] == c[0][1]:
            if a[0][0] > c[0][0]:
                direction = "L"
            elif a[0][0] == c[0][0]:
                direction = None
            else:
                direction = "R"

        if a[0][1] == b[0][1]:
            if a[0][0] > b[0][0]:
                direction = "L"
            elif a[0][0] == b[0][0]:
                direction = None
            else:
                direction = "R"

    def moveDemon(self, a):
        demonCoordinate = []
        player1Coordinate = []
        player2Coordinate = []
        demonCoordinate.append(self.coords(a))
        player1Coordinate.append(self.coords(self.play))
        player2Coordinate.append(self.coords(self.play2))
        global direction
        direction = random.choice(['U', 'L', 'R', 'D'])
        self.moveDirection(demonCoordinate, player1Coordinate, player2Coordinate)
        if direction == 'U' and demonCoordinate[0][1] > 4 * m:
            self.move(a, 0, -24)
        elif direction == 'D' and demonCoordinate[0][1] < 4 * m + 24 * (2 * m - 1):
            self.move(a, 0, 24)
        elif direction == 'L' and demonCoordinate[0][0] > 4 * n:
            self.move(a, -24, 0)
        elif direction == 'R' and demonCoordinate[0][0] < 4 * n + 24 * (2 * n):
            self.move(a, 24, 0)

        global life1, life2, label10, label12

        if demonCoordinate == player1Coordinate:
            life1 -= 1
            if life1 == 0:
                messagebox.showinfo('提示', '游戏结束,玩家2获胜')
                self.Over()
            a = "生命:" + str(life1)
            label10.config(text=a)

        if demonCoordinate == player2Coordinate:
            life2 -= 1
            a = "生命:" + str(life2)
            label12.config(text=a)
            if life2 == 0:
                messagebox.showinfo('提示', '游戏结束,玩家1获胜')
                self.Over()

    def Over(self):
        global frame, frameplay1, frameplay2, createCanvas
        frame.pack_forget()
        frameplay1.pack_forget()
        frameplay2.pack_forget()
        createCanvas.delete()
        top10()

    def victoryPan(self):
        global victory, stop_threads
        player1Coordinate = []
        player2Coordinate = []
        player1Coordinate.append(self.coords(self.play))
        player2Coordinate.append(self.coords(self.play2))
        if str(player2Coordinate[0]) == '[' + str(4 * n + 24) + '.0, ' + str(4 * m + (2 * m - 1) * 24) + '.0]':
            self.stop = 1
            stop_threads = False
            top()
            if victory == 0:
                victory = 1
                messagebox.showinfo('提示', '游戏结束,玩家2获胜')
            self.Over()
        if str(player1Coordinate[0]) == '[' + str(4 * n + (2 * n - 1) * 24) + '.0, ' + str(
                4 * m + (2 * m - 1) * 24) + '.0]':
            self.stop = 1
            stop_threads = False
            top()
            if victory == 0:
                victory = 1
                messagebox.showinfo('提示', '游戏结束,玩家1获胜')
            self.Over()


# 无关紧要的
def close(event):
    global stop_threads, startOver, createCanvas, life1, life2, score1, score2, frame, pl, play, label10, label12, label13, ti, label11
    if ti <= 580:
        stop_threads = False
        top()
    play.stop = 1
    del play
    createCanvas.pack_forget()
    createCanvas.delete()
    top10()


# 玩家一信息面板
def playerPanel1():
    global time_label
    btn000 = Button(frameplay1, text="重新开始", command=start)
    btn000.pack(pady=10)
    btn001 = Button(frameplay1, text=" 返    回 ", command=REturn)
    btn001.pack(pady=10)
    btn002 = Button(frameplay1, text=" 暂    停 ", command=stopp)
    btn002.pack(pady=10)
    time_label = Label(frameplay1, text='600', font=('', 15))
    time_label.pack(fill=BOTH, expand=YES)
    label09 = Label(frameplay1, text="方向键移动\n按p拾取金币\n按Alt+z键退出游戏", width=28, height=4,
                    bd=3)
    label09.pack(fill=BOTH, expand=YES)
    global label10, label11
    a = "生命：" + str(life1)
    label10 = Label(frameplay1, text=a, width=28, height=2, bd=3)
    label10.pack(fill=BOTH, expand=YES)
    b = "得分" + str(score1)
    label11 = Label(frameplay1, text=b, width=28, height=2, bd=3)
    label11.pack(fill=BOTH, expand=YES)


# 重新开始函数
def start():
    global stop_threads, frameplay1, frameplay2, startOver, createCanvas, life1, life2, score1, score2, frame, pl, play, label10, label12, label13, ti, label11
    createCanvas.pack_forget()
    frameplay1.pack_forget()
    frameplay2.pack_forget()
    createCanvas.delete()
    play.stop = 1
    del play
    stop_threads = False
    top()
    MapCreator(n, m, p)
    life1 = 100
    life2 = 100
    score1 = 0
    score2 = 0
    a = "生命:" + str(life1)
    label10.config(text=a)
    a = "生命:" + str(life2)
    label12.config(text=a)
    b = "得分" + str(score1)
    label11.config(text=b)
    b = "得分" + str(score2)
    label13.config(text=b)
    createCanvas = Canvas(frame)
    frameplay1.pack(side="left", fill=BOTH, expand=YES)
    createCanvas.pack(side="left", fill=BOTH, expand=YES)
    frameplay2.pack(side="left", fill=BOTH, expand=YES)
    play = player(createCanvas)
    _thread.start_new_thread(update, ())


# 暂停函数
def stopp():
    os.system("pause")


# 游戏内返回函数
def REturn():
    global stop_threads, startOver, createCanvas, life1, life2, score1, score2, frame, pl, play, label10, label12, label13, label11, frameplay1, frameplay2
    createCanvas.pack_forget()
    createCanvas.delete()
    frameplay1.pack_forget()
    frameplay2.pack_forget()
    frame.pack_forget()
    play.stop = 1
    del play
    stop_threads = False
    top()
    MapCreator(n, m, p)
    life1 = 100
    life2 = 100
    score1 = 0
    score2 = 0
    a = "生命:" + str(life1)
    label10.config(text=a)
    a = "生命:" + str(life2)
    label12.config(text=a)
    b = "得分" + str(score1)
    label11.config(text=b)
    b = "得分" + str(score2)
    label13.config(text=b)
    createCanvas = Canvas(frame)
    setUp()
    frame.pack()


# 玩家二信息面板
def playerPanel2():
    global time_label1
    btn000 = Button(frameplay2, text="重新开始", command=start)
    btn000.pack(pady=10)
    btn001 = Button(frameplay2, text=" 返    回 ", command=REturn)
    btn001.pack(pady=10)
    btn002 = Button(frameplay2, text=" 暂    停 ", command=stopp)
    btn002.pack(pady=10)
    time_label1 = Label(frameplay2, text='600', font=('', 15))
    time_label1.pack(fill=BOTH, expand=YES)
    label08 = Label(frameplay2, text="w向上\na向左 s向下 d向右\n按q拾取金币\n按Alt+z键退出游戏", width=28, height=4,
                    bd=3)
    label08.pack(fill=BOTH, expand=YES)
    global label12, label13
    a = "生命：" + str(life2)
    label12 = Label(frameplay2, text=a, width=28, height=2, bd=3)
    label12.pack(fill=BOTH, expand=YES)
    b = "得分" + str(score1)
    label13 = Label(frameplay2, text=b, width=28, height=2, bd=3)
    label13.pack(fill=BOTH, expand=YES)


def close1(event):
    global root
    root.destroy()


# 游戏创建
def Game():
    global frame, frameplay1, frameplay2, root, wall, e, gold, pr, pl, createCanvas
    root = Tk()
    root.title("迷宫游戏")
    root.attributes('-fullscreen', True)
    root.bind("<Alt-KeyPress-z>", close)
    root.bind("<Alt-KeyPress-x>", close1)
    setUp()
    wall = PhotoImage(file="photo/wall.gif")
    e = PhotoImage(file="photo/e.gif")
    gold = PhotoImage(file="photo/gold.gif")
    pr = PhotoImage(file="photo/pr.gif")
    pl = PhotoImage(file="photo/pl.gif")
    frame = Frame(root, width=n * 2 * 24 + n * m + 48 * n * 2, height=m * 2 * 24 + n * m + 48 * m * 2, bd=3, bg="pink")
    frameplay1 = Frame(frame, width=48 * n, height=48 * m, bd=3, bg="pink")
    frameplay2 = Frame(frame, width=24 * 2 * n, height=24 * 2 * m, bd=3, bg="pink")
    createCanvas = Canvas(frame)
    playerPanel1()
    playerPanel2()
    root.mainloop()


def top():
    global user, user2, ti
    if ti >= 580:
        return
    sql = 'insert into top values("' + str(user.get()) + '","' + str(ti) + '",' + str(score1) + ',' + str(
        life1) + ',' + str(ti + score1 * 3000 + life1 * 300) + ')'
    cursor.execute(sql)
    db.commit()
    if playerMachine == 0:
        sql = 'insert into top values("' + '人机' + '","' + str(ti) + '",' + str(score2) + ',' + str(
            life2) + ',' + str(ti + score2 * 3000 + life2 * 300) + ')'
        cursor.execute(sql)
        db.commit()
    elif playerMachine == 2:
        pass
    else:
        sql = 'insert into top values("' + str(user2.get()) + '","' + str(ti) + '",' + str(score2) + ',' + str(
            life2) + ',' + str(ti + score2 * 3000 + life2 * 300) + ')'
        cursor.execute(sql)
        db.commit()


def re():
    global frame, topFrame, createCanvas
    topFrame.pack_forget()
    topFrame.destroy()
    createCanvas = Canvas(frame)
    setUp()


def top10():
    global createCanvas, frame, frameplay1, frameplay2, topFrame
    frame.pack_forget()
    createCanvas.pack_forget()
    createCanvas.delete()
    frameplay1.pack_forget()
    frameplay2.pack_forget()
    topFrame = Frame(root, width=900, height=400, bd=5)
    topFrame.pack()
    sql = "SELECT * FROM top ORDER BY zonghe DESC;"
    cursor.execute(sql)
    all = cursor.fetchall()
    j = 1
    label = Label(topFrame, text='  历史战绩top10榜！  ', font=('宋体', 23)).grid(row=0, column=0, pady=10, columnspan=2)
    label = Label(topFrame, text='排名 玩家名 时间 得分 生命 评分', font=('宋体', 18)).grid(row=1, column=0,
                                                                                            columnspan=2)
    for i in all:
        label = Label(topFrame, text="top" + str(j), font=('宋体', 20)).grid(row=j + 2, column=0, padx=5)
        label = Label(topFrame, text=i, font=('宋体', 23)).grid(row=j + 2, column=1, pady=10)
        j = j + 1
        if j == 11:
            break
    label = Label(topFrame, text="ALT+x退出", font=('宋体', 23)).grid(row=j + 2, column=0, pady=10)
    bt0 = Button(topFrame, text="返 回！", command=re)
    bt0.grid(row=13, column=1)


if __name__ == '__main__':
    use = 'root'
    psw = '200174al'
    db = pymysql.connect(host='localhost', user=use, password=psw, charset='utf8', db='mysql')
    # 创建游标对象
    cursor = db.cursor()

    life1 = 100
    life2 = 100
    score1 = 0
    score2 = 0
    n = 15
    m = 14
    p = 20
    es = 1000
    eqi = 60

    tianmei()
    loginUi()
    cursor.close()
    db.close()
